import { deletedRecord, pageRecord, updateState } from '@/services/api/api-assess-week-culture-record';
import { CheckCircleFilled, CloseCircleOutlined } from '@ant-design/icons';
import { ActionType, DrawerForm, ProColumns, ProTable } from '@ant-design/pro-components';
import { useAccess } from '@umijs/max';
import { Button, message, Modal, Radio, RadioChangeEvent, Tag, Typography } from 'antd';
import Search from 'antd/lib/input/Search';
import React, { useRef, useState } from 'react';
import DetailRecord from './DetailRecord';
const { Paragraph } = Typography;
interface BanStateRecordReleaseMediaProps {
  areaId: string;
  areaName: string;
  releaseTimes: Array<string>; //季度发布时间范围
  onRefurbish: () => void;
}

const BanStateRecordReleaseMedia: React.FC<BanStateRecordReleaseMediaProps> = ({
  areaId,
  areaName,
  releaseTimes,
  onRefurbish,
}) => {
  const access = useAccess();
  const actionRef = useRef<ActionType>();

  const [queryParams, setQueryParamsState] = useState<any>({ releaseTimes: releaseTimes });

  const columns: ProColumns<AssessWeekCultureRecordData.RecordPage>[] = [
    {
      title: '级别',
      key: 'datahubSourceName',
      dataIndex: 'datahubLevelName',
      width: '40px',
      render: (dom, record, _index, action) => {
        return (
          <Tag
            color={
              record?.datahubLevelId === '1000'
                ? 'error'
                : record?.datahubLevelId === '2000'
                ? 'warning'
                : 'success'
            }
          >
            {record?.datahubLevelName}
          </Tag>
        );
      },
    },
    {
      title: '来源名称',
      key: 'datahubSourceName',
      dataIndex: 'datahubSourceName',
      width: '100px',
      render: (dom, record, _index, action) => {
        return <Tag color="orange">{record?.datahubSourceName}</Tag>;
      },
    },
    {
      title: '版面类型',
      key: 'datahubFocusId',
      dataIndex: 'datahubFocusId',
      width: '100px',
      render: (dom, record, _index, action) => {
        return <Tag color="orange">{record?.datahubFocusId}</Tag>;
      },
    },
    {
      title: '标题',
      dataIndex: 'name',
      align: 'center',
      width: '280px',
      ellipsis: true,
      render: (dom, record, _index, action) => {
        return (
          <div
            style={{
              textAlign: 'left',
              textOverflow: 'ellipsis',
              whiteSpace: 'nowrap',
              overflow: 'hidden',
            }}
          >
            <DetailRecord
              recordId={record.id}
              recordName={record.name}
              areaId={areaId}
              areaName={areaName}
              releaseTimes={releaseTimes}
              onRefurbish={function (): void {
                actionRef.current?.reload();
              }}
            />
          </div>
        );
      },
    },
    {
      title: '发布时间',
      key: 'releaseTime',
      dataIndex: 'releaseTime',
      valueType: 'date',
      width: '80px',
      align: 'center',
    },
    {
      title: '操作',
      key: 'option',
      width: '100px',
      valueType: 'option',
      render: (dom, record, _index, action) => [
        <a
          key="state"
          onClick={() => {
            if (record.state == 0) {
              //管理员下架的

              if (access.文化报表x配置x管理员 && access.文化报表x考核) {
                Modal.confirm({
                  title: '上架',
                  icon: (
                    <CheckCircleFilled
                      style={{
                        color: '#1677FF',
                      }}
                    />
                  ),
                  content: '上架后，该条报道相关联的区域都将参与评分计算',
                  async onOk() {
                    const response = await updateState({
                      id: record.id,
                    });

                    if (response.code == 0) {
                      message.success('已上架所有区域！');
                      actionRef.current?.reload();
                      Modal.destroyAll();
                    }
                  },
                });
              } else {
                Modal.error({
                  title: '警告',
                  icon: (
                    <CloseCircleOutlined
                      style={{
                        color: '#FF4D4F',
                      }}
                    />
                  ),
                  content: '该记录是由管理员下架，不能修改！',
                });
              }
            } else {
              Modal.confirm({
                title: '上架',
                icon: (
                  <CheckCircleFilled
                    style={{
                      color: '#1677FF',
                    }}
                  />
                ),
                content: `该条记录由${areaName}下架。
                上架后，该条报道将参与${areaName}评分计算`,
                async onOk() {
                  const response = await updateState({
                    id: record.id,
                    areaId: areaId,
                  });

                  if (response.code == 0) {
                    message.success('已上架！');
                    actionRef.current?.reload();
                    Modal.destroyAll();
                  }
                },
              });
            }
          }}
        >
          {record.state === 0 ? (
            access.文化报表x配置x管理员 ? (
              <Typography.Text type="success">上架</Typography.Text>
            ) : (
              <Typography.Text delete>上架</Typography.Text>
            )
          ) : record.banStateArea === 1 ? (
            <Typography.Text type="success">上架</Typography.Text>
          ) : (
            <></>
          )}
        </a>,
        <a
          key="deleted"
          onClick={() => {
            Modal.confirm({
              title: '删除',
              icon: (
                <CloseCircleOutlined
                  style={{
                    color: '#FF4D4F',
                  }}
                />
              ),
              content: '删除后，该条报道所关联的区域将不参与评分计算',
              okText: `仅删除${areaName}`,
              okButtonProps: {
                style: {
                  background: 'orange',
                  color: 'white',
                },
              },
              footer: (_, { OkBtn, CancelBtn }) => (
                <>
                  <CancelBtn />
                  <OkBtn />
                  <Button
                    type="primary"
                    danger
                    hidden={!(access.文化报表x配置x管理员 && access.文化报表x考核)}
                    onClick={async () => {
                      const response = await deletedRecord({
                        id: record.id,
                      });

                      if (response.code == 0) {
                        message.success('已删除所有！');
                        actionRef.current?.reload();
                        Modal.destroyAll();
                      }
                    }}
                  >
                    删除所有区域
                  </Button>
                </>
              ),
              async onOk() {
                const response = await deletedRecord({
                  id: record.id,
                  areaId: areaId,
                });

                if (response.code == 0) {
                  message.success('已删除！');
                  actionRef.current?.reload();
                  Modal.destroyAll();
                }
              },
            });
          }}
        >
          删除
        </a>,
      ],
    },
  ];

  return (
    <DrawerForm
      title={
        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
          <div>下架库</div>
        </div>
      }
      resize={{
        onResize() {
          console.log('resize!');
        },
        maxWidth: window.innerWidth * 0.8,
        minWidth: 400,
      }}
      trigger={
        <Button
          key="primary"
          type="primary"
          style={{
            backgroundColor: 'orange',
          }}
        >
          下架
        </Button>
      }
      submitter={false}
      autoFocusFirstInput
      drawerProps={{
        destroyOnClose: true,
        width: 900,
      }}
      onOpenChange={(visible) => {}}
      submitTimeout={2000}
      onFinish={async (values) => {}}
    >
      <ProTable<AssessWeekCultureRecordData.RecordPage>
        ghost
        headerTitle={
          <>
            <Radio.Group
              buttonStyle="solid"
              defaultValue={'all'}
              onChange={(e: RadioChangeEvent) => {
                console.log('=====', e);

                const datahubLevelId = e.target.value;
                setQueryParamsState({
                  ...queryParams,
                  datahubLevelIds: datahubLevelId == 'all' ? ['1000', '2000'] : [e.target.value],
                });
                actionRef.current?.reloadAndRest();
              }}
            >
              <Radio.Button value="all">全部</Radio.Button>
              <Radio.Button value="1000">中央媒体</Radio.Button>
              <Radio.Button value="2000">市属媒体</Radio.Button>
            </Radio.Group>
          </>
        }
        columns={columns}
        request={async (params = {}) => {
          const response = await pageRecord({
            areaId: areaId,
            types: [1, 2],
            state: 0,
            ...queryParams,
            ...params,
          });
          return Promise.resolve({
            data: response.data.data,
            total: response.data.total,
            success: response.code === 0,
          });
        }}
        actionRef={actionRef}
        scroll={{
          x: '1000px',
        }}
        toolbar={{
          actions: [
            <Search
              placeholder="请输入标题"
              onSearch={(value) => {
                setQueryParamsState({
                  ...queryParams,
                  name: value,
                });
                actionRef.current?.reloadAndRest();
              }}
              style={{ width: 200 }}
            />,
          ],
        }}
        rowKey="id"
        search={false}
      />
    </DrawerForm>
  );
};
export default BanStateRecordReleaseMedia;
